package com.caigou.modules.channel.ui

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.channel.R
import com.caigou.modules.channel.adapter.MedalItemAdapter
import com.caigou.modules.channel.bean.MedalBean
import com.caigou.modules.channel.databinding.FragmentMedalBinding
import com.caigou.modules.channel.viewmodel.ChannelViewModel
import com.caigou.modules.channel.widget.MedalDetailDialog
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/10/12
 */
@AndroidEntryPoint
class MedalFragment : BaseFragment() {

    private var _binding: FragmentMedalBinding? = null
    private val binding get() = _binding!!

    private val channelViewModel: ChannelViewModel by viewModels()

    private val taskAdapter: MedalItemAdapter by lazy {
        MedalItemAdapter(mutableListOf())
    }

    private val contestAdapter: MedalItemAdapter by lazy {
        MedalItemAdapter(mutableListOf())
    }

    private val famousAdapter: MedalItemAdapter by lazy {
        MedalItemAdapter(mutableListOf())
    }

    private var medalDetailDialog: MedalDetailDialog? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentMedalBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        binding.medalSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                channelViewModel.getMedalList(AppBackgroundInfo.instance.userBean!!.userId)
            }
        }

        binding.medalTaskLayout.taskRecyclerView.run {
            layoutManager = GridLayoutManager(requireActivity(), 3)
            adapter = taskAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

        binding.medalContestLayout.contestRecyclerView.run {
            layoutManager = GridLayoutManager(requireActivity(), 3)
            adapter = contestAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

        binding.medalFamusLayout.famousRecyclerView.run {
            layoutManager = GridLayoutManager(requireActivity(), 3)
            adapter = famousAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

        taskAdapter.setOnItemClickListener { adapter, view, position ->
            val item = taskAdapter.getItem(position)
            medalDetailDialog?.apply {
                dismiss()
                medalDetailDialog = null
            }
            medalDetailDialog = MedalDetailDialog(item, requireActivity())
            medalDetailDialog?.apply {
                btnWear.setOnClickListener {
                    channelViewModel.wearMedal(item.wearStatus, item.id.toString(), AppBackgroundInfo.instance.userBean!!.userId)
                }
                btnReceiver.setOnClickListener {
                    channelViewModel.receiverMedal(item.id.toString(), AppBackgroundInfo.instance.userBean!!.userId)
                }
                show()
            }
        }

        contestAdapter.setOnItemClickListener { adapter, view, position ->
            val item = taskAdapter.getItem(position)
            medalDetailDialog?.apply {
                dismiss()
                medalDetailDialog = null
            }
            medalDetailDialog = MedalDetailDialog(item, requireActivity())
            medalDetailDialog?.apply {
                btnWear.setOnClickListener {
                    channelViewModel.wearMedal(item.wearStatus, item.id.toString(), AppBackgroundInfo.instance.userBean!!.userId)
                }
                btnReceiver.setOnClickListener {
                    channelViewModel.receiverMedal(item.id.toString(), AppBackgroundInfo.instance.userBean!!.userId)
                }
                show()
            }
        }

        famousAdapter.setOnItemClickListener { adapter, view, position ->
            val item = taskAdapter.getItem(position)
            medalDetailDialog?.apply {
                dismiss()
                medalDetailDialog = null
            }
            medalDetailDialog = MedalDetailDialog(item, requireActivity())
            medalDetailDialog?.apply {
                btnWear.setOnClickListener {
                    channelViewModel.wearMedal(item.wearStatus, item.id.toString(), AppBackgroundInfo.instance.userBean!!.userId)
                }
                btnReceiver.setOnClickListener {
                    channelViewModel.receiverMedal(item.id.toString(), AppBackgroundInfo.instance.userBean!!.userId)
                }
                show()
            }
        }

        binding.medalTvBack.setOnClickListener {
            (requireActivity() as ChannelActivity).onBackPressed()
        }
    }

    override fun lazyLoad() {
        channelViewModel.getMedalList(AppBackgroundInfo.instance.userBean!!.userId)
    }

    override fun onBack() {
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(channelViewModel.medalListLiveData, ::handleGetMedalList)
        observe(channelViewModel.wearMedalLiveData, ::handleWearMedal)
        observe(channelViewModel.receiveMedalLiveData, ::handleReceiveMedal)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleGetMedalList(result: Resource<MedalBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.medalSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取勋章信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.medalSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                taskAdapter.setList(result.data!!.taskMedalList)
                contestAdapter.setList(result.data!!.contestMedalList)
                famousAdapter.setList(result.data!!.famousMedalList)
            }
        }
    }

    private fun handleWearMedal(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.medalSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取勋章信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.medalSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
                medalDetailDialog?.dismiss()
                channelViewModel.getMedalList(AppBackgroundInfo.instance.userBean!!.userId)
            }
        }
    }

    private fun handleReceiveMedal(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.medalSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取勋章信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.medalSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
                medalDetailDialog?.dismiss()
                channelViewModel.getMedalList(AppBackgroundInfo.instance.userBean!!.userId)
            }
        }
    }
}